package org.yds.quality.function.dft;

import com.googlecode.aviator.AviatorEvaluator;
import com.googlecode.aviator.runtime.function.AbstractFunction;
import com.googlecode.aviator.runtime.type.AviatorLong;
import com.googlecode.aviator.runtime.type.AviatorObject;
import org.yds.quality.dto.GlassDftDTO;

import java.util.*;

public class SumIf extends AbstractFunction {

    @Override
    public AviatorObject call(Map<String, Object> env, AviatorObject listObj, AviatorObject conditionObj) {
        List<?> list = (List<?>) listObj.getValue(env);
        String condition = (String) conditionObj.getValue(env);

        long total = 0;
        List<String> dftGlassIds = new ArrayList<>(); // 记录满足条件的 glassId 列表
        for (Object item : list) {
            if (item instanceof GlassDftDTO) {
                GlassDftDTO glass = (GlassDftDTO) item; // 强转为 GlassDftDTO
                // 创建局部环境，并将 glass 和 glass.codes 绑定到下一个函数去
                Map<String, Object> localEnv = new HashMap<>(env);
                localEnv.put("glass", glass);
                boolean match = (boolean) AviatorEvaluator.execute(condition, localEnv);
                if (match) {
                    total++;
                    dftGlassIds.add(glass.getId()); // 记录满足条件的 glassId
                }
            }
        }

        // 将满足条件的 glassId 列表存入全局环境
        env.put("dftGlassIds", dftGlassIds);
        env.put("total", total);

        return AviatorLong.valueOf(total);
    }

    @Override
    public String getName() {
        return "SumIf";
    }


    // 新增方法：返回参数列表
    public List<String> getEventParams() {
        return Arrays.asList("dftGlassIds", "total");
    }

}